<?php defined('SYSPATH') or die('No direct script access.');

class Model_SupplierParser_Optlist extends Model_SupplierParser_Abstract
{
    protected $_optlist_url    = 'http://optlist.ru';                 // Урл =)
    protected $_suppliers_url  = 'http://optlist.ru/suppliers/?page=1167';      // Шаблон урла поиска
    protected $_supplier_goods_url = 'http://optlist.ru/supplier/%d/product/?page=1';
    
    public function parse()
    {
        
        header('Content-type: text/html; charset=UTF-8');        
		$data =  simplexml_load_file(DOCROOT.'data/feeds/supplier_info.xml');
        foreach($data->supplier as $supplier){
            
            /*$ext_id         = $this->_get_id($supplier_data);
            $name       = $this->_get_name($supplier_data);
            $type       = $this->_get_type($supplier_data);
            
            $volume = ""; 
            $min_order = ""; 
            $payment_options = ""; 
            $delivery_methods = "";
            $legal_person = ""; 
            $payment_details = ""; 
            $description = ""; 
            $buy_opt = ""; 
            $nalog_system = "";
            $categories = ""; 
            $contacts = ""; 
            $html = ""; 
            $url_suppliers = "http://optlist.ru/supplier/".$ext_id."/";
            //echo count($data->supplier);
            
            ORM::factory('supplier_optlist')->add_supplier($name, $type, $volume, $min_order, $payment_options, $delivery_methods,
                    $legal_person, $payment_details, $description, $buy_opt, $nalog_system, $categories, $contacts, $html, $url_suppliers);*/
            /*$supp = ORM::factory('supplier_optlist', $supplier->id);
            $supp->type             = trim($supplier->type);
            $supp->min_order        = trim($supplier->min_order);
            $supp->volume           = trim($supplier->volume);
            $supp->payment_options  = trim($supplier->payment_options);
            $supp->delivery_methods = trim($supplier->delivery_methods);
            $supp->legal_person     = trim($supplier->legal_person);
            $supp->description      = trim($supplier->description);
            $supp->buy_opt          = trim($supplier->buy_opt);
            $supp->nalog_system     = trim($supplier->nalog_system);
            $supp->address          = trim($supplier->address);
            $supp->phone            = trim($supplier->phone);
            $supp->worktime         = trim($supplier->worktime);
            $supp->website          = trim($supplier->website);
            
            $supp->save(); */
            //echo "<pre>";
            //print_r($supplier->categories);
            try {
                foreach($supplier->categories->children() as $cat){
                    //echo $cat->ext_id . "<br>";
                    //var_dump($cat);
                    $query = DB::insert('supplier_categories', array('supplier_id', 'category_id'))->values(array($supplier->id, $cat->ext_id));
                    $query->execute();
                }
            } catch (Database_Exception $e) {
                if (strstr($e->getMessage(), 'Duplicate entry') !== false) {
                    
                } else {
                    die($e->getMessage());
                }
            }
            //die();
            //echo "<pre>";
            //print_r($supp);
            
            //echo View::factory('profiler/stats');
            //die();
        }
        /*//$this->_suppliers_url
        while ($page_data = $this->_get_page_data()) {
            //echo $page_data;
            //die(); 
            //usleep(700000);		
            while ($supplier_data = $this->_get_supplier_data($page_data)) {
                
                $ext_id         = $this->_get_id($supplier_data);
                $name       = $this->_get_name($supplier_data);
                $type       = $this->_get_type($supplier_data);
                
                $volume = ""; 
                $min_order = ""; 
                $payment_options = ""; 
                $delivery_methods = "";
                $legal_person = ""; 
                $payment_details = ""; 
                $description = ""; 
                $buy_opt = ""; 
                $nalog_system = "";
                $categories = ""; 
                $contacts = ""; 
                $html = ""; 
                $url_suppliers = "http://optlist.ru/supplier/".$ext_id."/";
                //echo $ext_id. " - " . $name .  " - ". $type . "<br>";
                
                ORM::factory('supplier_optlist')->add_supplier($name, $type, $volume, $min_order, $payment_options, $delivery_methods,
                    $legal_person, $payment_details, $description, $buy_opt, $nalog_system, $categories, $contacts, $html, $url_suppliers);
            }
            echo  $this->_suppliers_url . "<br>";
            //die();  
        }*/  
    }
    
    public function parse_payment_details()
    {
        $query = DB::select()
                ->from('suppliers')->where('payment_details', '=', "")->order_by('id', 'ASC');
        //$query->where('name', '=', "");
        $suppliers = $query
                ->execute()
                ->as_array();
        //echo count($suppliers);
        //die();
        foreach($suppliers as $supplier){
            $url_suppliers = $supplier['url_suppliers'];
            //$url_suppliers = "http://optlist.ru/supplier/26838/";
            //$data = $this->_get_source_code($url_suppliers);
            //$payment_details = $this->_cut_str('<p id="bank_info_box">', '</p>', $data);
            echo $url_suppliers . "<br>";
            //die();
            /*$query = DB::update('suppliers')
                            ->set(array('payment_details' => $payment_details))->
                                        where('id', '=', $supplier['id'])->execute();*/    
        }  
    }
    
    public function parse_goods_info()
    {
        //$goods = ORM::factory('goods_optlist')->
        $query = DB::select()
                ->from('goods');
        $query->where('name', '=', "");
        $names = $query
                ->execute()
                ->as_array();
        //$words = array();
        echo count($names) . "<br>";
        
        foreach($names as $name){
           //echo $name['id'] . " - ". $name['name'] . "<br>";
           $url = "http://optlist.ru".$name['url'];
           $data = $this->_get_source_code($url);
           
           $name_goods = $this->_cut_str('<h1 class="product_header">', '</h1>', $data);
           
           echo $name['id'] . " - " . $name_goods . "<br>";
           $goods = ORM::factory('goods_optlist', $name['id']);
           $goods->name = $name_goods;
           $goods->save();
           //die();
        }
    }
    
    public function parse_goods()
    {
        /// Выберем список поставщиков
        $suppliers = ORM::factory('supplier_optlist')->get_suppliers();
        //echo count($suppliers);
        //die();
        $count = 0;
        foreach($suppliers as $supplier){
            
            //print_r($supplier);
            
            $url = $supplier->url_suppliers."product/?page=1";
            //$url = "http://optlist.ru/supplier/16640/product/?page=1";
            echo $supplier->id . " - " . $url . "<br>";
            while($url){
                $data = $this->_get_source_code($url);
                
                /// Товары тянем
                $data = $this->_cut_str('<h1 class="like_h2">Каталог товаров</h1>', '<aside>', $data);
                
                $goods_url = "";
                $goods_img = "";
                $goods_name = "";
                $goods_price = "";
                $goods_desc = "";
                while($goods = $this->_cut_str('<div class="clearfix">', '<hr class="clear" />', $data)){
                    $goods_url = $this->_cut_str('<a href="', '">', $goods);
                    $goods_img = $this->_cut_str('<img src="', '" ', $goods);
                    $goods_name = $this->_cut_str('alt="', '" ', $goods);
                    $goods_price = $this->_cut_str('<p class="narrow">', '</p>', $goods);
                    $goods_desc = $this->_cut_str('<p class="narrow">', '</p>', $goods);
                
                /// добавить товар в бд
                ORM::factory('goods_optlist')->add_goods($supplier->id, $goods_name, $goods_price, $goods_desc, $goods_img, $goods_url);
                ///
                //echo $supplier->id. "<br>";
                    /*echo $goods_url. "<br>";
                    echo $goods_img. "<br>";
                    echo $goods_name. "<br>";
                    echo $goods_price. "<br>";
                    echo $goods_desc. "<br>===========<br>";
                    */
                    $count++;
                    //echo $count . "<br>";
                }
                   
                
                if($page = $this->_cut_str('<span class="current page">', '</span>', $data)){
                    if ($button_next = $this->_cut_str('class="button">Далее', '</a>', $data)) {
                        $page++;
                        //echo "### ". $page . "<br>";
                        $url = $supplier->url_suppliers."product/?page=".$page;      
                    } else {
                        $url = null;
                    }         
                } else {
                    break;
                }
                    
            }
            
            /*echo "<pre>";
            print_r($supplier);
            die(); */
            //sleep(1);
            usleep(500000);
        }
        /*echo "<pre>";
        print_r($suppliers);  */
        // Пармим постранично товары каждого поставщика
        
        // добавляем в бд товары             
    }
    
    /*public function get_reviews_urls($model)
    {
        $urls = array();
        $model_name = trim(str_replace(array('2Gb', '4Gb', '8Gb', '16Gb', '32Gb'), '', $model->name));
        $data = $this->_get_source_code($this->search_url . urlencode($model_name));
        $data = $this->_cut_str('<table class=catproduct>', '</table>', $data); 
        while ($product = $this->_cut_str('<tr>', '</tr>', $data)) {
            $url  = $this->otzovik_url . $this->_cut_str('<a href=', '>', $product);            
            $name = strip_tags($this->_cut_str('<td class=nprods>', '</td>', $product));
            if (strstr(Model_Main::get_clean_name($name), Model_Main::get_clean_name($model_name)) !== false) {
                $urls[] = $url;
                echo '<span style="color: red;">' . $name . '</span> - ' . $url . '<br />';   
            }
        }                                 
        return $urls;
    } 
    
    protected function _get_reviews_urls($url)
    {
        $urls = array();
        $this->reviews_url = $url;
        while ($page_data = $this->_get_page_data()) {
            //usleep(700000);
			sleep(5);
            while ($url = $this->_get_next_review_url($page_data)) {
                $urls[] = $url;    
            }    
        }
        return $urls;
    }     */
    
    protected function _get_page_data()
    {
        if (!$this->_suppliers_url) {
            return null;
        }
        
        $data = $this->_get_source_code($this->_suppliers_url); 
               
        // пихаем в $this->_suppliers_url адрес следущей страницы
        $this->_suppliers_url = $this->_get_next_page_url($data);
        
        //echo $this->_suppliers_url;
        //die();
        
        return $data;
    }
    
    protected function _get_next_page_url($data)
    {
        if ($url = $this->_cut_str('&nbsp; <a href="', '" class="button">', $data)) {
            return 'http://optlist.ru/suppliers/' . $url;      
        }     
        return null;    
    }
	
	protected function _get_supplier_data(&$data)
    {
        if ($_data = $this->_cut_str('<article>', '</article>', $data)) {
            return $_data;    
        }
        return null;
    }
    
    /*protected function _get_next_review_url(&$data)
    {
        if ($url = $this->_cut_str('<h3>', '</h3>', $data)) {
            if ($url = $this->_cut_str('<a href=', '>', $url)) {
                return $this->otzovik_url . $url; 
            }   
        }
        return null;   
    }*/
    
    protected function _get_id($data)
    {
        if ($id = $this->_cut_str('<a href="/supplier/', '/"', $data)) {
            return $id;    
        }
        return null;
    }
    
    protected function _get_name($data)
    {
        if ($name = $this->_cut_str(' target="_blank">', '</a>', $data)) {
            return trim(strip_tags(str_replace("&nbsp;", ' ', $name)));   
        }
        return null;
    }
    
    protected function _get_type($data)
    {
        $data = $this->_cut_str('<div class="item_info">', '<div class="item_buy_amount">', $data);
        $data = $this->_cut_str('title="', 'strong>', $data);
        
        if ($type = $this->_cut_str('">', '</', $data)) {
            return $type;  
        }
        return null;
    }
    
    protected function _get_date($data)
    {       
        if ($date = trim($this->_cut_str('Дата отзыва:</b>', '</span', $data))) {
			$date = substr($date, 0, 10);
			$parts = explode('-', $date);
			$result = array();
			
			if (count($parts) == 3) {
				$result['d'] = $parts[2];
				$result['m'] = $parts[1];
				$result['y'] = $parts[0];   
			} else {
				return null;
			}
			
			$date = strtotime(implode('-', $result));
			if ($date) {
				return $date;
			}                 
        }
        return null;
    }
    
    protected function _get_rating($data)
    { 
		return substr_count($data, 'rating_star_y');
		/*$count = 0;
        while ($this->_cut_str('class=\'rating_star_y', '</div', $data) !== null) { 
			$count++;
        }
        return $count; */  
    }
    
    protected function _get_pluses(&$data)
    {
        if ($pluses = $this->_cut_str('style=\'padding-top:5px\'><b>Достоинства:</b>', '</p', $data)) {
            return trim($pluses);    
        }
        return null;  
    }
    
    protected function _get_minuses(&$data)
    {
        if ($minuses = $this->_cut_str('style=\'padding-top:5px\'><b>Недостатки:</b>', '</p', $data)) {
            return trim($minuses);    
        }
        return null;  
    }
    
    protected function _get_text($data)
    {
        if ($text = $this->_cut_str('style=\'padding-top:5px\'>', '<b', $data)) {
            return trim(strip_tags($text));    
        }
        return null;   
    }
    
    
    protected function _get_usefulness($data)
    {
        $usefulness = array();
        $usefulness['yes'] = 0;
        if ($yes = $this->_cut_str('Отзыв рекомендуют:', '</b', $data)) {
			$usefulness['yes'] = (int)strip_tags($yes);          
        }
        $usefulness['no'] = 0;
        return $usefulness;
    }
}

/*
$_urls = $this->_get_reviews_urls($url);
foreach ($_urls as $_url) {
	//usleep(700000);
	sleep(5);
	$review_data = $this->_get_source_code($_url);          
	
	$id              = $this->_get_id($review_data);
	$user_link       = $this->_get_user_link($review_data);
	$user_nick       = $this->_get_user_nick($review_data);
	$date            = $this->_get_date($review_data);
	$rating          = $this->_get_rating($review_data);
	$link            = $_url;
	
	$pluses          = $this->_get_pluses($review_data);
	$minuses         = $this->_get_minuses($review_data);
	$text            = $this->_get_text($review_data);
	$u               = $this->_get_usefulness($review_data);
	
	try {
		ORM::factory('otzovik_reviews')->add_review($this->model, $id, $text, $pluses, $minuses, $rating,
			$user_nick, $link, $date, $u['yes'], $u['no'], $visible);
	} catch (Database_Exception $e) {
		if (strstr($e->getMessage(), 'Duplicate entry') !== false) {
			continue;
		}
		die($e->getMessage());
	}   
	
	echo 'id - '.$id.'<br />';
	echo 'user_nick - '.$user_nick.'<br />'; 
	echo 'user_link - '.$user_link.'<br />'; 
	echo 'date - '.date('d-M-y', $date).'<br />'; 
	echo 'rating - '.$rating.'<br />';
	echo 'link - '.$link.'<br />';  
	//echo 'pluses - '.$pluses.'<br />'; 
	//echo 'minuses - '.$minuses.'<br />'; 
	//echo 'text - '.$text.'<br />'; 
	print_r($u);
	echo '<hr />';    
} */ 